package com.lintf.flowable.config;

import com.lintf.common.base.AjaxResult;
import com.lintf.common.exception.ServiceException;
import com.lintf.common.utils.string.StringUtils;
import com.lintf.flowable.token.exception.NoLoginException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

import javax.servlet.http.HttpServletRequest;

/**
 * @author lin tingfeng
 * @system Mac
 * @data 2024/7/16 11:32
 * @package_name com.lintf.springaichat.config
 * @project_name spring-ai
 * @desc
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 业务异常
     */
    @ExceptionHandler(ServiceException.class)
    public AjaxResult handleServiceException(ServiceException exception, HttpServletRequest request) {
        log.error(exception.getMessage(), exception);
        Integer code = exception.getCode();
        return StringUtils.isNotNull(code) ? AjaxResult.error(code, exception.getMessage()) : AjaxResult.error(exception.getMessage());
    }

    /**
     * 未登录异常
     */
    @ExceptionHandler(NoLoginException.class)
    public AjaxResult handleNoLoginException(NoLoginException exception, HttpServletRequest request) {
        log.error(exception.getMessage(), exception);
        return AjaxResult.error(401, exception.getMessage());
    }

    /**
     * 请求方式不支持
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public AjaxResult handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException e,
                                                          HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',不支持'{}'请求", requestURI, e.getMethod());
        return AjaxResult.error(e.getMessage());
    }

    /**
     * 拦截未知的运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public AjaxResult handleRuntimeException(RuntimeException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',发生未知异常.", requestURI, e);
        return AjaxResult.error(e.getMessage());
    }

    /**
     * 系统异常
     */
    @ExceptionHandler(Exception.class)
    public AjaxResult handleException(Exception exception, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',发生系统异常.", requestURI, exception);
        return AjaxResult.error(exception.getMessage());
    }

    /**
     * 文件超出大小异常
     *
     * @param exc
     * @return
     */
    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public AjaxResult handleMaxSizeException(MaxUploadSizeExceededException exc) {
        log.error(exc.getMessage());
        return AjaxResult.error("上传的文件大小超过限制!");
    }

}
